package com.aclass.xqx.classscreen.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.aclass.xqx.classscreen.BaseApplication;
import com.aclass.xqx.classscreen.IMyAidlInterface;
import com.aclass.xqx.classscreen.bean.API;
import com.aclass.xqx.classscreen.bean.HomeBean;
import com.aclass.xqx.classscreen.bean.NewsBean;
import com.aclass.xqx.classscreen.db.AddData;
import com.aclass.xqx.classscreen.db.CardDao;
import com.aclass.xqx.classscreen.db.CardStudent;
import com.aclass.xqx.classscreen.db.CardTeacher;
import com.aclass.xqx.classscreen.db.Cardnumber;
import com.aclass.xqx.classscreen.db.ClassAlbum;
import com.aclass.xqx.classscreen.db.ClassLabour;
import com.aclass.xqx.classscreen.db.ClassSchedule;
import com.aclass.xqx.classscreen.db.Dynamic;
import com.aclass.xqx.classscreen.db.DynamicSchool;
import com.aclass.xqx.classscreen.db.StudentNews;
import com.aclass.xqx.classscreen.utlis.AppUtlis;
import com.aclass.xqx.classscreen.utlis.AsyncTaskSoapUtil;
import com.aclass.xqx.classscreen.utlis.ClassCalendar;
import com.aclass.xqx.classscreen.utlis.Constant;
import com.aclass.xqx.classscreen.utlis.LocationUtlis;
import com.aclass.xqx.classscreen.utlis.OkhttPost;
import com.aclass.xqx.classscreen.utlis.PrefUtild;
import com.google.gson.Gson;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

/**
 * Created by xqx on 2017/11/10.
 * 更新服务
 */
public class LocalService extends Service  {
    private ServiceConnection conn;
    private MyService myService;
    Intent intent = new Intent();
    List<String> studentList=new ArrayList<>();//删除学生
    List<String> LessonId=new ArrayList<>();//删除课程表
    List<String> AlbumId=new ArrayList<>();//删除相册
    List<String> ArtClassId=new ArrayList<>();//删除动态
    List<String> ArtSchoolId=new ArrayList<>();//删除动态
    List<String> TeacherId=new ArrayList<>();//删除老师
    List<String> LabourId=new ArrayList<>();//删除值日生
    @Override
    public IBinder onBind(Intent intent) {
        return myService;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
        AlarmManager();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String class_no = PrefUtild.INSTANCE.getString(getApplicationContext(), "class_no", "");
                String News = PrefUtild.INSTANCE.getString(getApplicationContext(),Constant.NEWS, "");
                if (!class_no.equals("")){
                    if (!News.equals("")) {
                        OkhttPost.Okget(API.NEWS + "?sno="+Constant.SNO+"&class_no=" + class_no, 1, new ServiceClaa());
                    }
                    OkhttPost.Okget(API.HOME+Constant.SNO+"/"+class_no+"?app_no="+android.os.Build.SERIAL,2,new ServiceClaa());
                }

            }
        },1000,10000);
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                String class_no = PrefUtild.INSTANCE.getString(getApplicationContext(), "class_no", "");
//                if (!class_no.equals("")){
////                    OkhttPost.Okget(API.HOME+"98/"+class_no,2,new ServiceClaa());
//                }
//
//            }
//        },1000,15000);
    }
    private void init() {
        if (conn == null) {
            conn = new MyServiceConnection();
        }
        myService = new MyService();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent intents = new Intent();
        intents.setClass(this, RemoteService.class);
        bindService(intents, conn, Context.BIND_IMPORTANT);
        return START_STICKY;
    }

    class MyService extends IMyAidlInterface.Stub {
        @Override
        public String getName() throws RemoteException {
            return null;
        }
    }

    private class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("获取连接");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LocalService.this.startService(new Intent(LocalService.this,
                    RemoteService.class));
            LocalService.this.bindService(new Intent(LocalService.this,
                    RemoteService.class), conn, Context.BIND_IMPORTANT);
        }

    }
    public void AlarmManager(){
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        long triggerAtTime = System.currentTimeMillis();
        Intent intent = new Intent();
        intent.setAction(Constant.TO);
        sendBroadcast(intent);
        Log.e("ATG",triggerAtTime+"  ban");
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
        manager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime,AlarmManager.INTERVAL_HALF_HOUR   , pi);
//        manager.set(AlarmManager.RTC_WAKEUP,triggerAtTime,pi);
    }
    class ServiceClaa implements OkhttPost.Callback{
        @Override
        public void onError(Call call, Exception e, int id) {
            intent.setAction(Constant.ERR);
            intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+": 主页数据接口访问失败"+e.toString());
            sendBroadcast(intent);
        }
        @Override
        public void onResponse(String response, int id) {
            Gson gson=new Gson();
            if(id==1){
                try {
                    NewsBean newsBean = gson.fromJson(response, NewsBean.class);
                    if (newsBean.code==1) {
                        List<NewsBean.Data> datas = newsBean.data;
                        for (NewsBean.Data data : datas) {
                            List<StudentNews> studentNewses = CardDao.queryNews(data.id);
                            if (studentNewses.size() == 0) {
                                AddData.addStudentNews(data.id, data.message, data.student_no, data.add_time);
                                intent.setAction(Constant.NEWS);
                                sendBroadcast(intent);
                            }
                        }
                    }
                }catch (Exception e){}
            }else if(id==2){
                intent.setAction(Constant.ERR);
                intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+": 主页数据接口访问成功");
                sendBroadcast(intent);
                try {
                    HomeBean homeBean = gson.fromJson(response, HomeBean.class);
                    studentList.clear();
                    //老师更新
                    List<HomeBean.Class_Info> class_info = homeBean.class_info;
                    TeacherId.clear();
                    for (HomeBean.Class_Info classInfo:class_info) {
                        TeacherId.add(classInfo.teacher_no);
                        if (classInfo.card_no != null&&classInfo.classname!=null) {
                            List<CardTeacher> cardTeachers = CardDao.queryTeacherId(classInfo.teacher_no);
                            if (cardTeachers.size() != 0) {
                                if (!cardTeachers.get(0).getClassname().equals(classInfo.classname) || !cardTeachers.get(0).getTeacher_name().equals(classInfo.teacher_name)
                                        || !cardTeachers.get(0).getCard_no().equals(classInfo.card_no)) {
                                    AddData.addTeacher(classInfo.teacher_no,classInfo.card_no,classInfo.classname,classInfo.teacher_name);
                                    intent.setAction(Constant.NAME);
                                    sendBroadcast(intent);
                                }
                            } else {
                                    AddData.addTeacher(classInfo.teacher_no,classInfo.card_no,classInfo.classname,classInfo.teacher_name);
                                intent.setAction(Constant.NAME);
                                sendBroadcast(intent);
                            }
                        }
                    }
                    List<HomeBean.Teacher_list> teacher_lists = homeBean.teacher_list;
                    for (HomeBean.Teacher_list teacher_list:teacher_lists){
                        if (teacher_list.card_no!=null){
                            List<Cardnumber> cardnumbers = CardDao.queryLoveID(teacher_list.teacher_no);
                            if (cardnumbers.size()!=0){
                                if(!cardnumbers.get(0).getCardnumber().equals(teacher_list.card_no)){
                                    AddData.addCardNum(teacher_list.teacher_no, teacher_list.card_no, 2);
                                }
                            }else {
                                    AddData.addCardNum(teacher_list.teacher_no, teacher_list.card_no, 2);
                            }
                        }
                    }
                    HomeBean.AppInfo app_info = homeBean.app_info;
                    if (app_info!=null){
                        String encryption = PrefUtild.INSTANCE.getString(getApplicationContext(), Constant.ENCRYPTION, "");
                        if (!encryption.equals(app_info.is_encryption)) {
                            PrefUtild.INSTANCE.setString(getApplicationContext(), Constant.ENCRYPTION, app_info.is_encryption);
                            PrefUtild.INSTANCE.setString(getApplicationContext(), Constant.KEY, app_info.key);
                        }
                    }
                    //课程表更新
                    List<HomeBean.Lesson_list> lesson_list = homeBean.lesson_list;
                    LessonId.clear();
                    for (HomeBean.Lesson_list lessonList:lesson_list){
                        LessonId.add(lessonList.id);
                        if (lessonList.week_day!=null&&lessonList.end_time!=null&&lessonList.start_time!=null
                                &&lessonList.name!=null) {
                            List<ClassSchedule> classSchedules = CardDao.queryscheduleId(lessonList.id);
                            if (classSchedules.size() != 0) {
                                if (!lessonList.name.equals(classSchedules.get(0).getSubject_name()) || !lessonList.week_day.equals(classSchedules.get(0).getWeek_day())
                                        || !lessonList.start_time.equals(classSchedules.get(0).getStart_time()) || !lessonList.end_time.equals(classSchedules.get(0).getEnd_time())) {
                                    AddData.addSchedule(lessonList.id,lessonList.name,lessonList.week_day,lessonList.start_time,lessonList.end_time);
                                    intent.setAction(Constant.SCHEDULE);
                                    sendBroadcast(intent);
                                }
                            } else {
                                AddData.addSchedule(lessonList.id,lessonList.name,lessonList.week_day,lessonList.start_time,lessonList.end_time);
                                intent.setAction(Constant.SCHEDULE);
                                sendBroadcast(intent);
                            }
                        }
                    }
                    //学生更新
                    List<HomeBean.Class_list> class_list = homeBean.class_list;
                    studentList.clear();
                    for (HomeBean.Class_list student:class_list){
                        studentList.add(student.student_no);
                        if (student.card_no!=null&&student.student_no!=null) {
                            String headimg="无头像";
                            if (student.headimg!=null){
                                headimg=student.headimg;
                            }
                            List<CardStudent> cardStudents = CardDao.queryStudentId(student.student_no);
                            String honor_id=student.honor_id==null?"0":student.honor_id;
                            if (cardStudents.size() != 0) {
                                if (!cardStudents.get(0).getStudent_name().equals(student.name)|| !cardStudents.get(0).getStudent_url().equals(headimg)
                                        || !cardStudents.get(0).getCard_no().equals(student.card_no)||cardStudents.get(0).getHonor_id()!=Integer.parseInt(honor_id)) {
                                    AddData.addStudent(student.student_no,student.card_no,student.name,honor_id,headimg);
                                    intent.setAction(Constant.STUDYPROGRESS);
                                    sendBroadcast(intent);
                                }
                            } else {
                                AddData.addStudent(student.student_no,student.card_no,student.name,honor_id,headimg);
                                intent.setAction(Constant.STUDYPROGRESS);
                                sendBroadcast(intent);
                            }
                        }
                    }
                    List<HomeBean.Labour_list> labour_list = homeBean.labour_list;
                    LabourId.clear();
                    for (HomeBean.Labour_list list:labour_list){
                        LabourId.add(list.student_id);
                        if (list.week_day!=null&&list.student_name!=null){
                            List<ClassLabour> classLabours = CardDao.queryLabourId(list.student_id);
                            if (classLabours.size()!=0){
                                if (!classLabours.get(0).getStudentneme().equals(list.student_name)||!classLabours.get(0).getWeekday().equals(list.week_day)){
                                    AddData.addLabour(list.student_id, list.week_day, list.student_name, list.add_time);
                                    if (Integer.parseInt(list.week_day)==ClassCalendar.getWeekDays()){
                                        intent.setAction(Constant.LABOUR);
                                        sendBroadcast(intent);
                                    }
                                }
                            }else {
                                AddData.addLabour(list.student_id, list.week_day, list.student_name, list.add_time);
                                if (Integer.parseInt(list.week_day)==ClassCalendar.getWeekDays()){
                                    intent.setAction(Constant.LABOUR);
                                    sendBroadcast(intent);
                                }
                            }
                        }
                    }
                    List<HomeBean.Art_school> art_school = homeBean.art_school;
                    ArtSchoolId.clear();
                    for (HomeBean.Art_school artSchool:art_school){
                        List<DynamicSchool> dynamics = CardDao.queryArtschoolId(artSchool.id);
                        ArtSchoolId.add(artSchool.id);
                        if (dynamics.size()!=0){
                            if (!dynamics.get(0).getContent().equals(artSchool.content)||!dynamics.get(0).getTitle().equals(artSchool.title)){
                                AddData.addDynamicSchool(artSchool.id,artSchool.add_time,artSchool.content,artSchool.title);
                                intent.setAction(Constant.ARTSCHOOL);
                                sendBroadcast(intent);
                            }
                        }else{
                            AddData.addDynamicSchool(artSchool.id,artSchool.add_time,artSchool.content,artSchool.title);
                            intent.setAction(Constant.ARTSCHOOL);
                            sendBroadcast(intent);
                        }
                    }
                    ArtClassId.clear();
                    List<HomeBean.Art_class> art_class = homeBean.art_class;
                    for (HomeBean.Art_class artClass:art_class){
                        List<Dynamic> dynamics = CardDao.queryArtClasslId(artClass.id);
                        ArtClassId.add(artClass.id);
                        if (dynamics.size()!=0){
                            if (!dynamics.get(0).getContent().equals(artClass.content)){
                                Log.e("ATS",dynamics.get(0).getContent()+"   "+artClass.content);
                                AddData.addDynamic(artClass.id,artClass.add_time,artClass.content,artClass.title);
                                intent.setAction(Constant.ARTCLASS);
                                sendBroadcast(intent);
                            }
                        }else{
                            AddData.addDynamic(artClass.id,artClass.add_time,artClass.content,artClass.title);
                            intent.setAction(Constant.ARTCLASS);
                            sendBroadcast(intent);
                        }
                    }
                    List<HomeBean.Album> albums = homeBean.album;
                    AlbumId.clear();
                    for (HomeBean.Album album:albums){
                        AlbumId.add(album.id);
                        List<ClassAlbum> classAlba = CardDao.queryAlbumId(album.id);
                        if (classAlba.size()==0){
                            AddData.addAlbum(album.id,album.add_time,album.pic_path,album.type_id);
                            if (album.type_id.equals("2")){
                                intent.setAction(Constant.HONOR);
                                sendBroadcast(intent);
                            }else if(album.type_id.equals("1")){
                                intent.setAction(Constant.BANNER);
                                sendBroadcast(intent);
                            }
                        }

                    }
                    //删除学生
                    List<CardStudent> cardStudents = CardDao.queryStudent();
                    for (CardStudent student:cardStudents){
                        boolean contains = studentList.contains(student.getId());
                        if (!contains){
                            BaseApplication.getDaoInstant().getCardStudentDao().deleteByKey(student.getId());
                            BaseApplication.getDaoInstant().clear();
                        }
                    }
                    //删除老师
                    List<CardTeacher> cardTeachers = CardDao.queryTeacher();
                    for (CardTeacher teacher:cardTeachers){
                        boolean contains = TeacherId.contains(teacher.getId());
                        if (!contains){
                            BaseApplication.getDaoInstant().getCardTeacherDao().deleteByKey(teacher.getId());
                            BaseApplication.getDaoInstant().clear();
                        }
                    }
                    //删除课表
                    List<ClassSchedule> classSchedules = CardDao.querySchedule();
                    for (ClassSchedule schedule1:classSchedules){
                        boolean contains = LessonId.contains(schedule1.getId());
                        if (!contains){
                            BaseApplication.getDaoInstant().getClassScheduleDao().deleteByKey(schedule1.getId());
                            BaseApplication.getDaoInstant().clear();
                            intent.setAction(Constant.SCHEDULE);
                            sendBroadcast(intent);
                        }
                    }
                    //删除相册
                    List<ClassAlbum> classAlba = CardDao.queryAlbum();
                    for (ClassAlbum album:classAlba){
                        boolean contains = AlbumId.contains(album.getId());
                        if (!contains){
                            BaseApplication.getDaoInstant().getClassAlbumDao().deleteByKey(album.getId());
                            BaseApplication.getDaoInstant().clear();
                            if (album.getTypeid().equals("2")){
                                intent.setAction(Constant.HONOR);
                                sendBroadcast(intent);
                            }else if(album.getTypeid().equals("1")){
                                intent.setAction(Constant.BANNER);
                                sendBroadcast(intent);
                            }
                        }
                    }
                    //删除校园公告
                    List<DynamicSchool> dynamics = CardDao.queryArtschool();
                    for (DynamicSchool dynami1:dynamics){
                        boolean contains = ArtSchoolId.contains(dynami1.getId());
                        if (!contains){
                            BaseApplication.getDaoInstant().getDynamicSchoolDao().deleteByKey(dynami1.getId());
                            BaseApplication.getDaoInstant().clear();
                            intent.setAction(Constant.ARTSCHOOL);
                            sendBroadcast(intent);
                        }
                    }
                    //删除班级公告
                    List<Dynamic> dynamics1 = CardDao.queryArtClass();
                    for (Dynamic dynami1:dynamics1){
                        boolean contains = ArtClassId.contains(dynami1.getId());
                        if (!contains){
                            BaseApplication.getDaoInstant().getDynamicDao().deleteByKey(dynami1.getId());
                            BaseApplication.getDaoInstant().clear();
                            intent.setAction(Constant.ARTCLASS);
                            sendBroadcast(intent);
                        }
                    }
                    //删除值日生
                    List<ClassLabour> classLabours = CardDao.queryLabour();
                    for (ClassLabour labour:classLabours){
                        boolean contains = LabourId.contains(labour.getId());
                        if (!contains){
                            BaseApplication.getDaoInstant().getClassLabourDao().deleteByKey(labour.getId());
                            BaseApplication.getDaoInstant().clear();
                            if (Integer.parseInt(labour.getWeekday())==ClassCalendar.getWeekDays()){
                                intent.setAction(Constant.LABOUR);
                                sendBroadcast(intent);
                            }
                        }
                    }
                }catch (Exception e){}
            }
        }
    }
}
